import os
import glob
from flask import jsonify, send_file
from src.utils.util import Util
from src.utils.logger import log_info, log_error
from src.modules.file_manager import FileManager
from src.modules.openai_processor import OpenAIProcessor

class CopywritingController:
    """处理视频文案生成和导出的控制器"""
    
    def __init__(self):
        self.file_manager = FileManager(logger=self._log)
        # 默认提示词模板
        self.default_prompt = """
根据以下视频文本内容，创作一篇专业的营销文案：

{transcript}

请提供一个引人入胜的文案，包括以下部分：
1. 不要有空行
2. 简洁明了的开场白，迅速抓住读者注意力
3. 使用适当的语气和风格

保持文案简洁、有力。
"""
    def _gen_client(self, api_key):
        return OpenAIProcessor(api_key=api_key, logger=self._log)
    def _log(self, message, level="info"):
        """记录日志"""
        if level == "error":
            log_error(message)
        else:
            log_info(message)
    
    def process_videos_in_folder(self, folder_path, api_key):
        """
        处理文件夹中所有一级视频文件
        
        :param folder_path: 文件夹路径
        :return: 处理结果
        """
        try:
            if not os.path.isdir(folder_path):
                return jsonify({"success": False, "message": "提供的路径不是文件夹"})
            
            # 支持的视频格式
            video_extensions = ['*.mp4', '*.avi', '*.mkv', '*.mov', '*.flv', '*.wmv']
            
            # 查找文件夹中的所有视频文件
            video_files = []
            for ext in video_extensions:
                video_files.extend(glob.glob(os.path.join(folder_path, ext)))
                
            if not video_files:
                return jsonify({"success": False, "message": "文件夹中没有找到视频文件"})
                
            self._log(f"找到 {len(video_files)} 个视频文件")
            
            results = []
            for video_path in video_files:
                # 处理单个视频
                result = self._process_single_video(video_path, api_key)
                results.append(result)
                
            # 返回处理结果
            return jsonify({
                "success": True,
                "message": f"成功处理 {len(video_files)} 个视频文件",
                "results": results
            })
            
        except Exception as e:
            error_message = f"处理文件夹中的视频失败: {str(e)}"
            self._log(error_message, level="error")
            
            return jsonify({
                "success": False,
                "message": error_message
            })
    
    def _process_single_video(self, video_path, api_key):
        """
        处理单个视频，提取文本
        
        :param video_path: 视频文件路径
        :return: 处理结果
        """
        try:
            video_name = os.path.basename(video_path)
            self._log(f"开始处理视频: {video_name}")
            openai_processor = self._gen_client(api_key=api_key)
            # 从视频提取音频
            audio_result = openai_processor.extract_audio_from_video(video_path)
            
            if not audio_result["success"]:
                return {
                    "video_path": video_path,
                    "video_name": video_name,
                    "success": False,
                    "message": audio_result["message"]
                }
                
            # 使用Whisper API转录音频
            transcript_result = openai_processor.transcribe_audio(audio_result["audio_path"])
            
            if not transcript_result["success"]:
                return {
                    "video_path": video_path,
                    "video_name": video_name,
                    "success": False,
                    "message": transcript_result["message"]
                }
                
            # 保存转录文本
            text_path = os.path.splitext(video_path)[0] + ".txt"
            with open(text_path, "w", encoding="utf-8") as f:
                f.write(transcript_result["text"])
                
            self._log(f"视频 {video_name} 处理成功")
            
            return {
                "video_path": video_path,
                "video_name": video_name,
                "success": True,
                "transcript": transcript_result["text"],
                "transcript_path": text_path
            }
            
        except Exception as e:
            error_message = f"处理视频 {os.path.basename(video_path)} 失败: {str(e)}"
            self._log(error_message, level="error")
            
            return {
                "video_path": video_path,
                "video_name": os.path.basename(video_path),
                "success": False,
                "message": error_message
            }
    
    def generate_copywriting(self, transcript, api_key, custom_prompt=None):
        """
        生成文案
        
        :param transcript: 视频文本内容
        :param custom_prompt: 自定义提示词
        :return: API响应
        """
        try:
            # 使用默认提示词或自定义提示词
            prompt = custom_prompt if custom_prompt else self.default_prompt
            
            # 填入文本内容
            full_prompt = prompt.format(transcript=transcript)
            openai_processor = self._gen_client(api_key=api_key)  # 假设API密钥已在初始化时设置
            # 生成文案
            result = openai_processor.generate_text(full_prompt)
            
            if not result["success"]:
                return jsonify(result)
                
            return jsonify({
                "success": True,
                "message": "文案生成成功",
                "copywriting": result["text"]
            })
            
        except Exception as e:
            error_message = f"文案生成失败: {str(e)}"
            self._log(error_message, level="error")
            
            return jsonify({
                "success": False,
                "message": error_message
            })
    
    def export_to_excel(self, data_list):
        """
        将文案导出到Excel
        
        :param data_list: 数据列表，包含video_name和copywriting
        :return: API响应，提供Excel文件下载
        """
        try:
            # 调用扩展后的Util类导出Excel
            export_result = Util.export_copywritings_to_excel(data_list)
            
            if not export_result["success"]:
                return jsonify(export_result)
                
            # 创建下载响应
            file_path = export_result["file_path"]
            file_name = os.path.basename(file_path)
            
            return send_file(
                file_path,
                mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                as_attachment=True,
                download_name=file_name
            )
            
        except Exception as e:
            error_message = f"Excel导出失败: {str(e)}"
            self._log(error_message, level="error")
            
            return jsonify({
                "success": False,
                "message": error_message
            })
    
    def get_default_prompt(self):
        """
        获取默认提示词
        
        :return: API响应
        """
        try:
            return jsonify({
                "success": True,
                "prompt": self.default_prompt
            })
            
        except Exception as e:
            error_message = f"获取默认提示词失败: {str(e)}"
            self._log(error_message, level="error")
            
            return jsonify({
                "success": False,
                "message": error_message
            })
            
            
    def generate_copywritings_batch(self, transcripts, api_key=None, custom_prompt=None):
        """
        批量生成文案
        
        :param transcripts: 文本内容数组，每个元素包含id、content和video_name
        :param api_key: OpenAI API密钥
        :param custom_prompt: 自定义提示词
        :return: API响应
        """
        try:
            # 获取OpenAI处理器
            openai_processor = self._gen_client(api_key)
            
            # 使用默认提示词或自定义提示词
            prompt_template = custom_prompt if custom_prompt else self.default_prompt
            
            # 批量处理结果
            results = []
            successful_count = 0
            
            # 遍历所有文本内容
            for transcript_item in transcripts:
                try:
                    transcript_id = transcript_item.get('id', '')
                    transcript_content = transcript_item.get('content', '')
                    video_name = transcript_item.get('video_name', '')
                    
                    self._log(f"处理文本 ID: {transcript_id}, 视频: {video_name}")
                    
                    # 如果内容为空，跳过
                    if not transcript_content:
                        results.append({
                            "id": transcript_id,
                            "video_name": video_name,
                            "success": False,
                            "message": "文本内容为空"
                        })
                        continue
                    
                    # 填入文本内容
                    full_prompt = prompt_template.format(transcript=transcript_content)
                    
                    # 生成文案
                    result = openai_processor.generate_text(full_prompt)
                    
                    if not result["success"]:
                        results.append({
                            "id": transcript_id,
                            "video_name": video_name,
                            "success": False,
                            "message": result["message"]
                        })
                        continue
                    
                    # 添加成功结果
                    successful_count += 1
                    results.append({
                        "id": transcript_id,
                        "video_name": video_name,
                        "success": True,
                        "copywriting": result["text"]
                    })
                    
                except Exception as e:
                    error_message = f"处理文本 {transcript_item.get('id', '')} 失败: {str(e)}"
                    self._log(error_message, level="error")
                    
                    results.append({
                        "id": transcript_item.get('id', ''),
                        "video_name": transcript_item.get('video_name', ''),
                        "success": False,
                        "message": error_message
                    })
            
            # 返回所有结果
            return jsonify({
                "success": True,
                "message": f"已处理 {len(transcripts)} 个文本，成功 {successful_count} 个",
                "results": results
            })
            
        except Exception as e:
            error_message = f"批量生成文案失败: {str(e)}"
            self._log(error_message, level="error")
            
            return jsonify({
                "success": False,
                "message": error_message
            })